// import Divmod
// import Nevow.Athena

ChatThing.ChatterBox = Nevow.Athena.Widget.subclass('ChatThing.ChatterBox');

ChatThing.ChatterBox.methods(
    function __init__(self, node) {
        ChatThing.ChatterBox.upcall(self, "__init__", node);
        self.chooseBox = self.nodeByAttribute('name', 'chooseBox');
        self.chatBox = self.nodeByAttribute('name', 'chatBox');
        self.scrollArea = self.nodeByAttribute('name', 'scrollArea');
        self.loginsArea = self.nodeByAttribute('name', 'loginsArea');
        self.usernameField = self.nodeByAttribute('name', 'username');
        self.userMessage = self.nodeByAttribute('name', 'userMessage');
        self.loggedInAs = self.nodeByAttribute('name', 'loggedInAs');
    },

    function doSetUsername(self) {
        var username = self.usernameField.value;
        self.callRemote("setUsername", username).addCallback(
            function (result) {
                self.chooseBox.style.display = "none";
                self.chatBox.style.display = "block";
                self.loggedInAs.appendChild(document.createTextNode(username));
                self.loggedInAs.style.display = "block";
            });
        return false;
    },

    function doSay(self) {
        self.callRemote("say", self.userMessage.value);
        self.nodeByAttribute('name', 'userMessage').value = "";
        return false;
    },

    function displayMessage(self, message) {
        var newNode = document.createElement('div');
        newNode.appendChild(document.createTextNode(message));
        self.scrollArea.appendChild(newNode);
        document.body.scrollTop = document.body.scrollHeight;
    },

    function displayLogins(self, message) {
        var newNode = document.createElement('div');
        newNode.appendChild(document.createTextNode(message));
        self.loginsArea.appendChild(newNode);
        document.body.scrollTop = document.body.scrollHeight;
    },

    function updateMessage(self, message, div) {
        var newNode = document.createElement('p');
	newNode.innerHTML = message;
        //newNode.appendChild(document.createTextNode(message));
	if (div == 'scrollArea') {
	  self.scrollArea.appendChild(newNode);
	} else if (div == 'loginsArea') {
	  self.loginsArea.appendChild(newNode);
	} else {
	  alert('unhandled error');
	}
        document.body.scrollTop = document.body.scrollHeight;
    },

    function displayUserMessage(self, avatarName, text) {
        var msg = avatarName+': '+text;
        self.displayMessage(msg);
    });
